package com.wjw.utils.mail;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc 邮件发送器 (带附件)
 * @author wjw
 * @date 2016年11月23日下午2:23:31
 */
public class MailSendHelper  { 
	
    /**
     * 日志对象
     */
    protected static Logger log = LoggerFactory.getLogger(MailSendHelper.class);
	
	/** 邮件发送服务器的IP或域名 */
	private String host; 
	/** 登陆邮件发送服务器的用户名 */
	private String username;
	/** 登陆邮件发送服务器的密码 */
	private String password;
	/** 是否需要身份验证 */
	private boolean validate = true;
	
	public MailSendHelper() {
		// TODO Auto-generated constructor stub
	}
	
	public MailSendHelper(String host,String username,String password,Boolean validate) {
		// TODO Auto-generated constructor stub
		this.host=host;
		this.username=username;
		this.password=password;
		this.validate=validate;
	}
	
	/**
	 * 以TXT格式发送邮件 
	 * @param toAddress  邮件接收者的地址
	 * @param ccAddress  抄送人地址
	 * @param bccAddress 密送人地址
	 * @param subject 邮件主题
	 * @param content 邮件的文本内容 
	 * @param attachFileNames 邮件附件的文件名
	 * @return
	 */
	public boolean sendTextMail(String[] toAddress,String[] ccAddress,String[] bccAddress,String subject,String content,String[] attachFileNames) { 
		return sendMail(toAddress, ccAddress, bccAddress, subject, content, attachFileNames, false);
	}
	
	/**
	 * 以HTML格式发送邮件 
	 * @param toAddress  邮件接收者的地址
	 * @param ccAddress  抄送人地址
	 * @param bccAddress 密送人地址
	 * @param subject 邮件主题
	 * @param content 邮件的文本内容 
	 * @param attachFileNames 邮件附件的文件名
	 * @return
	 */
	public boolean sendHtmlMail(String[] toAddress,String[] ccAddress,String[] bccAddress,String subject,String content,String[] attachFileNames){
		return sendMail(toAddress, ccAddress, bccAddress, subject, content, attachFileNames, true);
	} 
	
	/**
	 * 发送邮件 
	 * @param toAddress  邮件接收者的地址
	 * @param ccAddress  抄送人地址
	 * @param bccAddress 密送人地址
	 * @param subject 邮件主题
	 * @param content 邮件的文本内容 
	 * @param attachFileNames 邮件附件的文件名
	 * @param isHtml 是否以html格式发送
	 * @return
	 */
	public boolean sendMail(String[] toAddress,String[] ccAddress,String[] bccAddress,String subject,String content,String[] attachFileNames,Boolean isHtml) { 
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Properties props = System.getProperties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth", validate?"true":"false");
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(session);
			// 创建邮件发送者地址
			Address from = new InternetAddress(username);
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
	
			// 接收人地址
			Address[] tolist = new Address[toAddress.length];
			int i = 0;
			for (String add : toAddress) {
				tolist[i++] = new InternetAddress(add);
			}
			mailMessage.setRecipients(Message.RecipientType.TO, tolist);
	
			// 抄送人地址
			if (ccAddress != null && ccAddress.length > 0) {
				Address[] cclist = new Address[ccAddress.length];
				i = 0;
				for (String add : ccAddress) {
					cclist[i++] = new InternetAddress(add);
				}
				mailMessage.setRecipients(Message.RecipientType.CC, cclist);
			}
	
			// 密抄送人地址
			if (bccAddress != null && bccAddress.length > 0) {
				Address[] bcclist = new Address[bccAddress.length];
				i = 0;
				for (String add : bccAddress) {
					bcclist[i++] = new InternetAddress(add);
				}
				mailMessage.setRecipients(Message.RecipientType.BCC, bcclist);
			}
	
			// 设置邮件消息的主题
			mailMessage.setSubject(subject);
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
	
			// MimeMultipart类是一个容器类，包含MimeBodyPart类型的对象 
			Multipart mp = new MimeMultipart();
			// 向Multipart添加正文
			MimeBodyPart mbpContent = new MimeBodyPart();
			if(isHtml){
				mbpContent.addHeader("Content-Type","text/html; charset=utf-8");
			}
			mbpContent.setContent(content, "text/html;charset=utf-8");
			// 向MimeMessage添加（Multipart代表正文）
			mp.addBodyPart(mbpContent);
			
			//设置附件
			String[] files = attachFileNames;
			if (files != null && files.length > 0) {
				for (String f : files) {
					// 建立第二部分：附件
					MimeBodyPart fileContent = new MimeBodyPart();
					// 获得附件
					DataSource source = new FileDataSource(f);
					// 设置附件的数据处理器
					fileContent.setDataHandler(new DataHandler(source));
					// 设置附件文件名
					fileContent.setFileName(f);
					// 加入第二部分
					mp.addBodyPart(fileContent);
				}
			}
			mailMessage.setContent(mp);
			
			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
			log.error("邮件发送错误！");
		}
		return false;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}
	
} 

